var http = require('http'),
  url = require('url');

// 用于请求的选项
var options = {
  host: '',
  port: '',
  path: '',
  method: '',
  headers: {}
};

/**
 * 根据不同的method进行填充请求数据
 * @param  {[string]} urlStr     [请求地址]
 * @param  {[string]} params     [请求参数]
 */
function fillOptions(urlStr, params, properties) {
  var urlObj = url.parse(urlStr);
  options.host = urlObj.hostname;
  options.port = urlObj.port;
  options.path = urlObj.pathname;
  if (options.method.toLowerCase() === 'get') {
    // if (typeof params === 'object' && params !== null) {
    //   var query = '?';
    //   for (var i in params) {
    //     query += (i + '=' + params[i] + '&');
    //   }
    //   query = query.substring(0, query.length - 1);
    // }
    options.path = urlObj.path;
  } else if (options.method.toLowerCase() === 'post') {

  } else {
    throw new Error('请求方法错误!');
  }
}

function send(callback) {
  var req = http.request(options, function(response) {
    var body = '';
    response.on('data', function(data) {
      body += data;
    });

    response.on('end', function() {
      if (body === '') {
        throw new Error('无响应结果!');
      }
      callback(body);
    });
  });
  req.end();
}

function sendPost(urlStr, params, callback) {
  options.method = 'post';
  fillOptions(urlStr, params);
  send(callback);
}

function sendGet(urlStr, params, callback) {
  options.method = 'get';
  fillOptions(urlStr, params, properties);
  send(callback);
}

sendGet('http://192.168.123.93:8280/payprod-merchant-front/payprod/order?a=1&b=2', { a: 1, b: 2 }, null, function(data) {
  console.log(data);
});
